package io.renren.modules.basedata.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.sdts.user.VehicleUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.sdts.user.VehicleUploadResponse;
import io.renren.common.utils.DateUtil;
import io.renren.common.utils.EmptyUtil;
import io.renren.modules.basedata.dao.VehicleDao;
import io.renren.modules.basedata.entity.Tbl_vehicle;
import io.renren.modules.basedata.service.VehicleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class VehicleServiceImpl implements VehicleService {
    private static final Logger log = LoggerFactory.getLogger(VehicleServiceImpl.class);
    @Autowired
    private VehicleDao vehicleDao;
    @Override
    public String vehicleUpload() throws Exception {

        log.info("开始获取未上传客户车辆信息");
        Tbl_vehicle vehicle=null;
        List<Tbl_vehicle> list = getVwhicleList();//获取未上传客户车辆户信息
        int operResult=0;
        String fileName ="";
        if(list!=null&&list.size()>0){
            for(int i=0;i<list.size();i++){
                vehicle = list.get(i);
                VehicleUploadRequest localVehicleUploadRequest=new VehicleUploadRequest();
                localVehicleUploadRequest.setId(vehicle.getId().trim());//必填  车牌颜色未确定的缺省值为9
                localVehicleUploadRequest.setUserId(vehicle.getUserId().trim());//必填
                localVehicleUploadRequest.setType(vehicle.getType());//必填
                if(vehicle.getUseCharacter()!=null&&vehicle.getUseCharacter()>0&&vehicle.getUseCharacter()<8){
                    localVehicleUploadRequest.setUseCharacter(vehicle.getUseCharacter());//非必填
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getOwnerName())){
                    try {
                        localVehicleUploadRequest.setOwnerName(vehicle.getOwnerName().trim());//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setOwnerName("默认名称");
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'机动车所有人名称OwnerName'失败，填充默认值'默认名称':"+e.getMessage());
                    }
                }
                if(vehicle.getOwnerIdType()!=null){
                    try {
                        localVehicleUploadRequest.setOwnerIdType(vehicle.getOwnerIdType());//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setOwnerIdType(199);
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'机动车所有人证件类型OwnerIdType'失败，填充默认值'199':"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getOwnerIdNum())){
                    try {
                        localVehicleUploadRequest.setOwnerIdNum(vehicle.getOwnerIdNum().trim());//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setOwnerIdNum("1234567890");
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'机动车所有人证件号OwnerIdNum'失败，填充默认值'1234567890':"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty(vehicle.getOwnerTel())){
                    try {
                        localVehicleUploadRequest.setOwnerTel(vehicle.getOwnerTel().trim());//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setOwnerTel("99999999999");//非必填
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'机动车所有人联系方式OwnerTel'失败，填充默认值'99999999999':"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getAddress())){
                    try {
                        localVehicleUploadRequest.setAddress(vehicle.getAddress());//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setAddress("默认地址");
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'机动车所有人地址Address'失败，填充默认值'默认地址':"+e.getMessage());
                    }
                }
                try {
                    localVehicleUploadRequest.setContact(vehicle.getContact().trim());//必填
                } catch (Exception e) {
                    localVehicleUploadRequest.setContact("0");
                    log.info("上传车辆信息'"+vehicle.getId()+"'填充'指定联系人姓名Contact'失败，填充默认值'0':"+e.getMessage());
                }
                localVehicleUploadRequest.setRegisteredType(vehicle.getRegisteredType());//必填 1-线上2-线下
                localVehicleUploadRequest.setChannelId(vehicle.getChannelId().trim());//必填  网点号
                localVehicleUploadRequest.setRegisteredTime(DateUtil.formatDateTimes(vehicle.getRegisteredTime()));//必填
                if("0".equals(vehicle.getVIN().trim())){
                    localVehicleUploadRequest.setVin("LSGJA52H8FS074656");//必填
                }else{
                    try {
                        localVehicleUploadRequest.setVin(vehicle.getVIN().trim());
                    } catch (Exception e) {
                        localVehicleUploadRequest.setVin("LSGJA52H8FS074656");
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'车辆识别代号VIN'失败，填充默认值'LSGJA52H8FS074656':"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getVehicleType())){
                    try {
                        localVehicleUploadRequest.setVehicleType(vehicle.getVehicleType().trim());//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setVehicleType("0");
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'行驶证车辆类型VehicleType'失败，填充默认值'0':"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getVehicleModel())){
                    try {
                        localVehicleUploadRequest.setVehicleModel(vehicle.getVehicleModel().trim());//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setVehicleModel("0");
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'行驶证品牌型号VehicleModel'失败，填充默认值'0':"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getEngineNum())){
                    try {
                        localVehicleUploadRequest.setEngineNum(vehicle.getEngineNum().trim());//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setEngineNum("0");
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'车辆发动机号EngineNum'失败，填充默认值'0':"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getRegisterDate())){
                    localVehicleUploadRequest.setRegisterDate(vehicle.getRegisterDate().trim());//非必填
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getIssueDate())){
                    localVehicleUploadRequest.setIssueDate(vehicle.getIssueDate().trim());//非必填
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getFileNum())){
                    localVehicleUploadRequest.setFileNum(vehicle.getFileNum().trim());//非必填
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getTotalMass())){
                    try {
                        localVehicleUploadRequest.setTotalMass(Integer.parseInt(vehicle.getTotalMass().trim()));//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setTotalMass(0);//非必填
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'总质量TotalMass'失败，填充默认值'0':"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getMaintenanceMass())){
                    try {
                        localVehicleUploadRequest.setMaintenanceMass(Integer.valueOf(vehicle.getMaintenanceMass().trim()));//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setMaintenanceMass(0);//非必填
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'整备质量MaintenanceMass'失败，填充默认值'0':"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getPermittedWeight())){
                    try {
                        localVehicleUploadRequest.setPermittedWeight(Integer.valueOf(vehicle.getPermittedWeight().trim()));//非必填
                    } catch (Exception e) {
                        if(vehicle.getType()>4){//货车
                            localVehicleUploadRequest.setPermittedWeight(0);//非必填
                            log.info("上传车辆信息'"+vehicle.getId()+"'填充'核定载质量PermittedWeight'失败，填充默认值'0':"+e.getMessage());
                        }else{//客车
                            localVehicleUploadRequest.setPermittedWeight(-1);//非必填
                            log.info("上传车辆信息'"+vehicle.getId()+"'填充'核定载质量PermittedWeight'失败，填充默认值'-1':"+e.getMessage());
                        }
                    }
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getPermittedTowWeight())){
                    try {
                        localVehicleUploadRequest.setPermittedTowWeight(Integer.valueOf(vehicle.getPermittedTowWeight().trim()));//非必填
                    } catch (Exception e) {
                        if(vehicle.getType()>4){//货车
                            localVehicleUploadRequest.setPermittedTowWeight(0);//非必填
                            log.info("上传车辆信息'"+vehicle.getId()+"'填充'准牵引总质量PermittedTowWeight'失败，填充默认值'0':"+e.getMessage());
                        }else{//客车
                            localVehicleUploadRequest.setPermittedTowWeight(-1);//非必填
                            log.info("上传车辆信息'"+vehicle.getId()+"'填充'准牵引总质量PermittedTowWeight'失败，填充默认值'-1':"+e.getMessage());
                        }
                    }
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getTestRecord())){
                    localVehicleUploadRequest.setTestRecord(vehicle.getTestRecord().trim());//非必填
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getOutsideDimensions())){
                    try {
                        localVehicleUploadRequest.setOutsideDimensions(vehicle.getOutsideDimensions().trim());//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setOutsideDimensions("4800X1500X1800");//非必填
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'外廓尺寸OutsideDimensions'失败，填充默认值'4800X1500X1800':"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty1(vehicle.getAxleDistance())){
                    try {
                        localVehicleUploadRequest.setAxleDistance(Integer.valueOf(vehicle.getAxleDistance().trim()));
                    } catch (Exception e) {
                        localVehicleUploadRequest.setAxleDistance(0);
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'轴距AxleDistance'失败，填充默认值'0':"+e.getMessage());
                    }
                }
                if(vehicle.getWheelCount()!=null){
                    try {
                        localVehicleUploadRequest.setWheelCount(vehicle.getWheelCount());//非必填
                    } catch (Exception e) {
                        localVehicleUploadRequest.setWheelCount(0);//非必填
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'车轮数WheelCount'失败，填充默认值'0':"+e.getMessage());
                    }
                }
                if(vehicle.getAxleCount()!=null){
                    try {
                        localVehicleUploadRequest.setAxleCount(vehicle.getAxleCount());
                    } catch (Exception e) {
                        localVehicleUploadRequest.setAxleCount(0);
                        log.info("上传车辆信息'"+vehicle.getId()+"'填充'车轴数AxleCount'失败，填充默认值'0':"+e.getMessage());
                    }
                }
                if(vehicle.getApprovedCount()!=null){
                    localVehicleUploadRequest.setApprovedCount(vehicle.getApprovedCount());//非必填
                }
//				if(vehicle.getAxleDistance()!=null){
//					localVehicleUploadRequest.setAxleDistance(Integer.valueOf(vehicle.getAxleDistance().trim()));//非必填
//				}
//				if(vehicle.getAxisType()!=null){
//					localVehicleUploadRequest.setAxlsType(vehicle.getAxisType());//非必填  JDK可能有问题
//				}
                if(vehicle.getFlag()==2){
                    localVehicleUploadRequest.setOperation(1);//必填 1-新增2-变更3-删除
                }else if(vehicle.getFlag()==3){
                    localVehicleUploadRequest.setOperation(2);//必填 1-新增2-变更3-删除
                }else{
                    localVehicleUploadRequest.setOperation(3);//必填 1-新增2-变更3-删除
                }
                System.out.println(localVehicleUploadRequest.toJsonStr());
                //获取发送文件名
                fileName = ETCCommHelper.getFileName(localVehicleUploadRequest,"65");
                //生成就json文件
//				CreateFileUtil.createJsonFile(request.toJsonStr(), "",fileName);
                try{
                    //指定响应的协议模型,调用upload发送数据
                    VehicleUploadResponse response = ETCCommHelper.sdtsUpload(fileName, localVehicleUploadRequest, VehicleUploadResponse.class);
                    log.info("上传客户车辆信息成功,服务器返回:"+response.toJson());
                    if(response!=null&&response.getInfo().equals("成功！")){
                        //上传成功,更新客户车辆信息表状态
                        if(localVehicleUploadRequest.getOperation()!=3){//非删除操作,只需更新数据库
                            if(vehicleDao.updateDelVehicleflag(vehicle.getId())==1){
                                log.info("更新客户车辆信息数据成功");
                                operResult ++;
                            }else{
                                log.info("更新客户车辆信息数据失败");
                            }
                        }else{//删除该条数据
//						if(sqlMapClient.delete("user_ORACLE.deleteUploadVehicleflag",vehicle.getId())==1){
                            if(vehicleDao.updateUploadVehicleflag(vehicle.getId())==1){
                                log.info("更新客户车辆信息数据成功");
                                operResult ++;
                            }else{

                                log.info("删除客户车辆信息数据失败");
                                vehicleDao.updateUploadVehicleflagError(vehicle.getId());

                            }
                        }

                    }else{

                        log.info("上传客户车辆信息失败,失败信息:"+response.getInfo());

                    }

                }catch(IOException e){

                    log.info("上传客户车辆信息失败,失败信息:"+e.getMessage());

                    continue;
                }catch(ApiRequestException apie){

                    log.info("上传客户车辆信息失败,失败信息:"+apie.getMessage());

                    if(apie.getErrCode()>=700&&apie.getErrCode()<=800){

                        if(apie.getErrCode()==707){
                            vehicleDao.updateUploadVehicleflag(vehicle.getId());

                        }else if(apie.getErrCode()==703||apie.getErrCode()==704){

                            vehicleDao.updateUploadVehicleflagError(vehicle.getId());

                        }

                    }

                    log.info("错误码:"+apie.getErrCode()+",错误信息:"+apie.getMessage());

                    continue;
                }
            }
            log.info("上传成功"+operResult+"条数据");
            return "客户车辆信息上传结束！";
        }else{
            return "无客户车辆信息,上传结束...";
        }
    }
    //获取充值信息
    @SuppressWarnings("unchecked")
    public List<Tbl_vehicle> getVwhicleList() throws Exception {
        List<Tbl_vehicle> list;
        try {
            list = vehicleDao.getUnuploadVehicleList();
        } catch (Exception e1) {
            e1.printStackTrace();
            log.error("获取未上传客户车辆信息失败!错误信息:", e1);
            throw new Exception("获取未上传客户车辆信息失败:"+e1.getMessage());
        }
        return list;
    }
}
